package com.yindian.cos.easy.security.authentication.login.social.core;

import com.yindian.cos.easy.security.authentication.login.UserDetail;
import com.yindian.cos.easy.security.authentication.login.social.SocialUserService;
import com.yindian.cos.easy.security.exception.AuthenticationException;
import com.yindian.cos.easy.security.exception.SocialRegisterNotifyParamsException;
import com.yindian.cos.easy.security.handler.AuthenticationFailureHandler;
import com.yindian.cos.easy.security.handler.LoginSuccessHandler;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

/**
 * 第三方登录controller
 *
 * @author zhangchuanhao
 * @create 2018/11/20
 */
@Log4j2
@RestController
public class SocialController {

    @Autowired(required = false)
    private UserInfoStore userInfoStore;

    @Autowired(required = false)
    private SocialUserService socialUserService;

    @Autowired(required = false)
    private LoginSuccessHandler loginSuccessHandler;

    @Autowired(required = false)
    private AuthenticationFailureHandler authenticationFailureHandler;

    /**
     * 第三方用户注册后回调
     * 需要把之前的UserInfo完整的回传，并且带上业务系统的userId
     *
     * @param userInfo
     * @param result
     * @param request
     * @param response
     * @throws IOException
     */
    @PostMapping("/social/register/notify")
    public void registerNotify(@Validated @Valid @RequestBody UserInfo userInfo,
                               BindingResult result,
                               HttpServletRequest request,
                               HttpServletResponse response) throws IOException {
        log.debug("{}登录注册回调：userInfo = {}", userInfo.getProvider(), userInfo);
        try {
            String errorMsg;
            if (result.hasErrors()) {
                for (FieldError error : result.getFieldErrors()) {
                    errorMsg = error.getDefaultMessage();
                    throw new SocialRegisterNotifyParamsException(errorMsg);
                }
            }
            if (userInfoStore != null) {
                userInfoStore.saveUserInfo(userInfo);
            }
            if (socialUserService != null) {
                UserDetail userDetail = socialUserService.getUserDetail(userInfo.getUserId());
                if (loginSuccessHandler != null) {
                    loginSuccessHandler.handler(request, response, userDetail);
                }
            }
        } catch (AuthenticationException ex) {
            if (authenticationFailureHandler != null) {
                authenticationFailureHandler.handler(request, response, ex);
            }
        }
    }
}
